package com.javastar.modules.security.service;

import cn.hutool.core.collection.CollectionUtil;
import com.javastar.common.exception.ErrorCode;
import com.javastar.common.redis.RedisKey;
import com.javastar.common.redis.RedisUtil;
import com.javastar.common.utils.ConvertUtils;
import com.javastar.common.utils.ValidatorUtils;
import com.javastar.modules.admin.entity.*;
import com.javastar.modules.security.bean.SysUserDetails;
import com.javastar.modules.sys.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 自定义用户名查询用户和权限信息
 *
 * @author zxx
 * @date 2023/7/25
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private SysUserService userService;
    @Autowired
    private SysRoleService roleService;
    @Autowired
    private SysMenuService menuService;
    @Autowired
    private SysRoleUserService roleUserService;
    @Autowired
    private SysRoleMenuService roleMenuService;
    @Autowired
    private RedisUtil redisUtil;

    /**
     * 根据用户名查询用户，并封装为自定义UserDetails对象返回
     * @param username the username identifying the user whose data is required.
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUserEntity sysUser = userService.lambdaQuery().eq(SysUserEntity::getUsername, username).one();
        if (ValidatorUtils.isEmpty(sysUser)) {
            throw new UsernameNotFoundException(ErrorCode.USERNAME_OR_PASSWORD_ERROR.getMsg());
        }
        return ConvertUtils.sourceToTarget(sysUser, SysUserDetails.class);
    }

    /**
     * 根据id查询详细、角色、权限信息，并封装返回
     * @param userId
     * @return
     */
    public SysUserDetails getUsernamePasswordAuthenticationTokenById(Long userId) {
        SysUserEntity sysUser = userService.getById(userId);
        SysUserDetails userDetails = ConvertUtils.sourceToTarget(sysUser, SysUserDetails.class);
        List<GrantedAuthority> authorities = new ArrayList<>();
        // 角色列表
        List<Long> roleIds = roleUserService.lambdaQuery().eq(SysRoleUserEntity::getUserId, userDetails.getId()).list().stream().map(SysRoleUserEntity::getRoleId).toList();
        if (CollectionUtil.isNotEmpty(roleIds)) {
            List<SimpleGrantedAuthority> roles = roleService.lambdaQuery().in(SysRoleEntity::getId, roleIds).list().stream().map(sysRoleEntity -> new SimpleGrantedAuthority("ROLE_" + sysRoleEntity.getName())).toList();
            authorities.addAll(roles);
            // 菜单权限列表
            List<Long> menuIds = roleMenuService.lambdaQuery().in(SysRoleMenuEntity::getRoleId, roleIds).list().stream().map(SysRoleMenuEntity::getMenuId).toList();
            if (CollectionUtil.isNotEmpty(menuIds)) {
                List<SimpleGrantedAuthority> permissions = menuService.lambdaQuery().in(SysMenuEntity::getId, menuIds).list().stream().map(sysMenuEntity -> new SimpleGrantedAuthority(sysMenuEntity.getPermissions())).toList();
                authorities.addAll(permissions);
            }
        }
        userDetails.setAuthorities(authorities);
        redisUtil.set(RedisKey.ADMIN_INFO, String.valueOf(userId), sysUser);
        if (!ValidatorUtils.isEmpty(authorities)) {
            redisUtil.set(RedisKey.ADMIN_PERMISSIONS, String.valueOf(userId), authorities.stream().map(authority -> authority.getAuthority()).toList());
        }
        return userDetails;
    }
}
